package cs271.examples.exceptions;

public class ExceptionExample {
    
    public void throwMyCheckedException() throws MyCheckedException {
        //will not compile without the throws statement
        throw new MyCheckedException();
    }

    public void throwMyRuntimeException() {
        //compiles just fine without a throws in the method signature
        throw new MyRuntimeException();
    }
    

    public void passOnCheckedException() throws MyCheckedException {
        this.throwMyCheckedException();
        System.out.println("Never printed inside passOnCheckedException()");
    }
    
    public void handleCheckedException() {
        try {
            this.throwMyCheckedException();
        } catch(MyCheckedException e) {
            System.out.println("Handling checked exception inside handleCheckedException()");
        }
    }
    
    public static void main(String[] args) {
        ExceptionExample test = new ExceptionExample();
        
        System.out.println("Catching runtime exceptions: ");
        try {
           test.throwMyRuntimeException();
        } catch(MyRuntimeException e) {
           System.out.println("Caught MyRuntimeException");
        }
        
        System.out.println("\nCatching checked exceptions: ");
        try {
            test.throwMyCheckedException();
            System.out.println("Never Printed.");
        } catch(MyCheckedException e) {
            System.out.println("Caught MyCheckedException");
        }
        
        System.out.println("\nLooking at the finally block: ");
        try {
            if(false)
                test.throwMyCheckedException();
        } catch(MyCheckedException e) {
            System.out.println("Won't be printed.");
        } finally {
            System.out.println("Always Printed.");
        }
        
        System.out.println("\nLooking at how exceptions can be passed up: ");
        try {
            test.passOnCheckedException();
        } catch(MyCheckedException e) {
            System.out.println("Passed the exception through another method, handled here.");
        }
        
        System.out.println("\nLooking at an already handled exception: ");
        test.handleCheckedException();
    }
}
